/* -----------------------------------------------------------------------------
 * PROJECT    : net.lwf
 * FILE       : LwfWorksheetAction.java
 *
 * HISTORY:
 * Date          Author                        Description
 * ----------------------------------------------------------------------------- 
 * Jan 27, 2011  mycodetalks			       Created
 */
package net.lwf.web.struts.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lwf.handler.IProcessHandler;
import lwf.web.struts.action.BaseAction;
import net.lwf.common.constant.ICommonConstant;
import net.lwf.entity.QuestionInfo;
import net.lwf.entity.UserPreferences;
import net.lwf.number.util.RandomNumberGenerator;
import net.lwf.util.web.WebUtil;
import net.lwf.web.constant.IWebConstant;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * Class description goes here
 */
public abstract class LwfWorksheetAction extends BaseAction {
	
	public ActionForward home(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		//Set form data
		LwfWorksheetActionForm aform = (LwfWorksheetActionForm) form;
		aform.setAskQuestion(false);
		return mapping.findForward("display");
	} //home	
	
	//private String operation;
	
//	public void resetOperation(HttpServletRequest request) {
//		WebUtil.setAttribute(request, IWebConstant.OPERATION, request.getParameter(IWebConstant.OPERATION));
//	}
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
//		this.operation = request.getParameter(IWebConstant.OPERATION);
//		if(this.operation != null) {
//			WebUtil.setAttribute(request, IWebConstant.OPERATION, request.getParameter(IWebConstant.OPERATION));
//		}
//		else {
//			Object obj = WebUtil.getAttribute(request, IWebConstant.OPERATION);
//			if(obj != null) {
//				this.operation = (String) obj;
//			}
//		}
		return super.execute(mapping, form, request, response);
	}
	
	//public abstract IProcessHandler getHandler(); this should be brought from BaseAction
	
	public ActionForward checkanswer(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// String useranswer = request.getParameter("useranswer");
		String useranswer = getUserAnswer(request);
		QuestionInfo lastattemptedQ = (QuestionInfo) WebUtil.getAttribute(request, "lastQuestion");
		PrintWriter out = response.getWriter();
		int apprimage = RandomNumberGenerator.generate(1, 12);
		String imagetag = ICommonConstant.EMPTY;
		String answermsg = "<font color=\"red\"> Your answer is wrong.... Please try again.</font>";
		if(!lastattemptedQ.isAnswered()) {
			imagetag = "<img src=\"" + request.getContextPath() + 
            "/image/appreciation/not ok " + String.valueOf(apprimage) + 
            ".gif\">&nbsp;&nbsp;";
			if (isMaxAttempts(request, lastattemptedQ.getAttempts())) {
				answermsg = "<font color=\"red\"> You have reached maximum number of attempts to answer this sum. <br> The correct answer is: ";
				if(lastattemptedQ.getFormattedAnswer() != null) {
					answermsg += lastattemptedQ.getFormattedAnswer();
				}
				else {
					answermsg += lastattemptedQ.getAnswer();
				}
				answermsg +=  "<br>Please click next for the next sum OR choose different operation.</font>";
				imagetag = "";
			} else {
				lastattemptedQ.attempted();
				//if (getHandler().matchAnswer(useranswer, lastattemptedQ.getAnswer())) {
				if (getHandler(request).matchAnswer(useranswer, lastattemptedQ)) {
					lastattemptedQ.setAnswered(true);
					answermsg = "<font color=\"blue\"> The answer is correct. You may click next for the next question. </font>";
					imagetag = "<img src=\"" + request.getContextPath()
							+ "/image/appreciation/ok " + String.valueOf(apprimage)
							+ ".gif\">&nbsp;&nbsp;";
					response.setContentType("text/html");
				}
				if (!displayAppreiciation(request)) {
					answermsg = "<font color=\"blue\"> You have already entered the correct answer. Please click next for the next question. </font>";
					imagetag = "";
				}
			}			
		}
		else {
			answermsg = "<font color=\"red\"> You have already answered the question. <br>"
				      + "Please click next for the next sum OR choose different operation.</font>";
		}

		//this.resetLastData(request, sumdetails);
		out.println(imagetag + answermsg);
		out.flush();

		return null; // Not forwarding to anywhere, response is fully-cooked

	}
	
	public boolean isMaxAttempts(HttpServletRequest request, int attempts) {
		UserPreferences preferences = getUserPreferences(request);
		if(preferences.getAttempts() == attempts) {
			return true;
		}
		
		return false;
	}
	
	private UserPreferences getUserPreferences(HttpServletRequest request) {
		return getWebUser(request).getPreferences();
	}
	
	private boolean displayAppreiciation(HttpServletRequest request) {
		UserPreferences userpref = getUserPreferences(request);
		if(userpref.getSeeAnswer().equals(ICommonConstant.YES)) {
			return true;
		}
		return false;
	}
	
	protected String getUserAnswer(HttpServletRequest request) {
		return request.getParameter("useranswer");
	}
	
/*	@SuppressWarnings("unchecked")
	public void setQuestionData(HttpServletRequest request, QuestionInfo question) {
		WebUtil.setAttribute(request, "lastQuestion", question);
		Object object = WebUtil.getAttribute(request, "qData");
		Map<String, List<AttemptedQuestion>> mapQData;
		List<AttemptedQuestion> attemptedQs = null;
		if(object == null) {
			mapQData = new HashMap<String, List<AttemptedQuestion>>();
		}
		else {
			mapQData = (Map<String, List<AttemptedQuestion>>) object;
		}
		
		String key = getQuestionKey(request);
		if(mapQData.containsKey(key)) {
			attemptedQs = mapQData.get(key);
		}
		else {
			attemptedQs = new ArrayList<AttemptedQuestion>();
		}
		attemptedQs.add(question);
		mapQData.put(key, attemptedQs);
		//Set question number
		WebUtil.setAttribute(request, "qData", mapQData);
		//Set Radio Answers
		WebUtil.setAttribute(request, IWebConstant.RADIO_ANSWERS, question.getRadioAnswerChoices());
	}
	
	@SuppressWarnings("unchecked")
	public int getQuestionNumber(HttpServletRequest request) {
		String key = getQuestionKey(request);
		Map<String, List<AttemptedQuestion>> mapQData 
		  = (Map<String, List<AttemptedQuestion>>) WebUtil.getAttribute(request, "qData");
		if(mapQData != null) {
			List<AttemptedQuestion> attemptedQs = mapQData.get(key);
			if(attemptedQs != null) {
				return attemptedQs.size();
			}
		}
		return 1;
	}*/
	@SuppressWarnings("unchecked")
	public void setQuestionData(HttpServletRequest request, QuestionInfo question) {
		WebUtil.setAttribute(request, "lastQuestion", question);
		Object object = WebUtil.getAttribute(request, "qData");
		Map<String, List<QuestionInfo>> mapQData;
		List<QuestionInfo> attemptedQs = null;
		if(object == null) {
			mapQData = new HashMap<String, List<QuestionInfo>>();
		}
		else {
			mapQData = (Map<String, List<QuestionInfo>>) object;
		}
		
		String key = getQuestionKey(request);
		if(mapQData.containsKey(key)) {
			attemptedQs = mapQData.get(key);
		}
		else {
			attemptedQs = new ArrayList<QuestionInfo>();
		}
		attemptedQs.add(question);
		mapQData.put(key, attemptedQs);
		//Set question number
		WebUtil.setAttribute(request, "qData", mapQData);
		//Set Radio Answers
		WebUtil.setAttribute(request, IWebConstant.RADIO_ANSWERS, question.getRadioAnswerChoices());
	}
	
	@SuppressWarnings("unchecked")
	public int getQuestionNumber(HttpServletRequest request) {
		String key = getQuestionKey(request);
		Map<String, List<QuestionInfo>> mapQData 
		  = (Map<String, List<QuestionInfo>>) WebUtil.getAttribute(request, "qData");
		if(mapQData != null) {
			List<QuestionInfo> attemptedQs = mapQData.get(key);
			if(attemptedQs != null) {
				return attemptedQs.size();
			}
		}
		return 1;
	}
	
	public String getQuestionKey(HttpServletRequest request) {
		//String grade = getGrade(request);
		String subject = getSubject(request);
		String topic = getTopic(request);
		String key = getGrade(request);
		if(subject != null) {
			if(topic != null) {
				key += "+" + subject + "+" + topic;
			}
			else {
				key += "+" + subject;
			}
		}
		return key;
	}
	
/*	
 	//Moved to BasicAction
 	public String getGrade(HttpServletRequest request) {
		return getUser(request).getUser().getGrade();
	}
	
	public String getSubject(HttpServletRequest request) {
		return WebUtil.getOptionalParameter(request, "subject"); //remove hard coding
	}
	
	public String getTopic(HttpServletRequest request) {
		return WebUtil.getOptionalParameter(request, "topic"); //remove hard coding
	}

	public String getOperation(HttpServletRequest request) {
		return (String) WebUtil.getAttribute(request, IWebConstant.OPERATION);
	}*/
	
	@Override
	public IProcessHandler getHandler(HttpServletRequest request) {
		return null;
	}

	//Moved to BasicAction
//	public void setBasicFormInfo(HttpServletRequest request, String title, String quizLink) {
//		FormBasicInfo info = new FormBasicInfo(title, quizLink);
//		setBasicFormInfo(request, info);
//	}
//	
//	public void setBasicFormInfo(HttpServletRequest request, String title, String quizLink, String pdfLink) {
//		FormBasicInfo info = new FormBasicInfo(title, quizLink, pdfLink);
//		setBasicFormInfo(request, info);
//	}
//	
//	public void setBasicFormInfo(HttpServletRequest request, String title) {
//		FormBasicInfo info = new FormBasicInfo(title);
//		setBasicFormInfo(request, info);
//	}
//	
//	public void setBasicFormInfo(HttpServletRequest request, FormBasicInfo info) {
//		request.setAttribute("basicFormInfo", info);
//	}
	
//	public String getOperation() {
//		return operation;
//	}

}



